from qa_engine.aiml import kernel_class
from qa_engine.user import User
from qa_engine.util import read_config_path


class BaseHandler:
    """
    问答处理程序基类
    """

    def __init__(self, config: dict):
        """
        :param config: 配置
        """
        self.config = config
        if 'aiml-kernel' in config.keys():
            self._register_aiml_kernel()
        else:
            self.aiml_kernels = {}

    def _register_aiml_kernel(self):
        """
        读取aiml核心的配置
        :return:
        """
        self.aiml_kernels = {}
        for each_kernel in self.config['aiml-kernel']:
            kernel = kernel_class[str(each_kernel['version'])]()
            for each_path in each_kernel['learn-from']:
                kernel.learn(read_config_path(each_path))
            if each_kernel['id'] in self.aiml_kernels.keys():
                from sys import stderr
                stderr.write('aiml kernel id duplicate: %s' % each_kernel['id'])
            self.aiml_kernels[each_kernel['id']] = kernel

    def handle(self, question: str, user: User = None, _position: str = ''):
        """
        根据输入回应, handler接口
        :param question: 问题
        :param user: 用户
        :param _position: 位置
        :return: 如果能够回应, 则返回回应 格式 str[], 否则 None
        """
        raise NotImplementedError
